package work.util.data.HsqlDb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HsqlDbUtil
{
	private static Connection	connexion		= null;

	public static final String	DATABASENAME	= "database";

	public static void connect()
	{
		connexion = createConnection(DATABASENAME);
	}

	public static Connection createConnection(String database)
	{
		try
		{
			Class.forName("org.hsqldb.jdbcDriver").newInstance();

			return DriverManager.getConnection("jdbc:hsqldb:file:" + database, "sa", "");
		}
		catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	public static void disconnect()
	{
		disconnect(connexion);
	}
	
	public static void disconnect(Connection connexion)
	{
		try
		{
			java.sql.Statement statement = connexion.createStatement();
			statement.execute("SHUTDOWN");
			statement.close();
			connexion.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	public static ResultSet executeQuery(String query)
	{
		return executeQuery(query, null, connexion);
	}
	
	public static ResultSet executeQuery(String query, Connection connexion)
	{
		return executeQuery(query, null, connexion);
	}

	public static ResultSet executeQuery(String query, Integer nbRow)
	{
		return executeQuery(query, nbRow, connexion);
	}
	
	public static ResultSet executeQuery(String query, Integer nbRow, Connection connexion)
	{
		try
		{
			Statement statement = connexion.createStatement();
			System.out.println("Query = " + query);
			if (nbRow != null)
				statement.setMaxRows(nbRow);
			ResultSet resultat = statement.executeQuery(query);
			return resultat;
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static int executeUpdate(String query)
	{
		return executeUpdate(query, connexion);
	}
	
	public static int executeUpdate(String query, Connection connexion)
	{
		try
		{
			Statement statement = connexion.createStatement();
			System.out.println("UpdateQuery = " + query);
			int resultat = statement.executeUpdate(query);
			return resultat;
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		return -1;
	}
}
